<?php

/**
 * ResultController
 * 
 * @author Radovan Dvorsky
 * @version 20100604
 */

require_once 'Zend/Controller/Action.php';

class ResultController extends Zend_Controller_Action {
	
	public function init(){
		$contextSwitch = $this->_helper->getHelper('AjaxContext');
        $contextSwitch->addActionContext('show-user', 'html')
        ->addActionContext('add-question-dialog', 'html')//nepouziva sa        
        ->addActionContext('add-question-number','html')
        ->addActionContext('add-additional-question','html')//nepouziva sa        
        ->addActionContext('add-result','html')
        ->addActionContext('add-thesis','html')
        ->addActionContext('add-thesis-mark','html')
        ->addActionContext('show-result-dialog', 'html')//nepouziva sa
        ->addActionContext('show-block','html')
        ->addActionContext('show-question','html')
        ->addActionContext('fill-students-panel','html')
        ->initContext();
	}
	
	/**
	 * The default action
	 * 
	 * Zobrazuje len lavy stlpec, ktory obsahuje mena studentov
	 */
	public function indexAction() {
		
		$cache = Zend_Registry::get('cache');		
		$cacheName = My_Support::getCacheName($this,'index');
		$url = $this->view->url(array(
			'controller' => 'result',
			'action' => 'fill-students-panel',
			'format' => 'html'
			)		
		);
		$this->view->groupSelectForm = new Form_Block_SelectGroup($url,'.treeContainer');
			
		if(!($students = $cache->load($cacheName))){
			$stutentMapper = new Db_Mapper_Student();			
			$students = $stutentMapper->fetchActualStudents();
			$cache->save($students,$cacheName,array('students'));
		}		
		
			
		$this->view->students = $students;				
	}
	
	
	/**
	 * Zobrazuje konkretneho uzivatela (pridelene bloky, tema bc. prace).
	 * Ak nie je pridelene cislo otazky, tak zobrazi formular. Rovnako aj pri
	 * teme bc. prace.
	 */
	public function showUserAction(){
				
		$ID_st = (int) $this->getRequest()->getParam('id');	
		$cache = Zend_Registry::get('cache');		
		$data = array();//bude obsahovat vsetky data z db, ktore sa ukladaju do cache
		
				
		/*
		 * Zisti ci ma pridelene cislo otazky
		 */
		$qnForStudentMapper = new Db_Mapper_QnForStudent();
		$hasQuestion = $qnForStudentMapper->hasQuestion(new Db_Model_Student(array('ID_st' => $ID_st)));		
	
		
		/*
		 * Ak nema pridelene cislo otazky, zobraz formular
		 */
		if(!$hasQuestion){
			$questionNumberForm = new Form_Result_AddQuestionNumber(null,$this->view->url(array(
				'controller' => 'result',
				'action' => 'add-question-number',
				'format' => 'html'
				)
			 ),$ID_st,'div.dataContainer');		
			
			$this->view->questionNumberForm = $questionNumberForm;
		}
		
		$cacheName = My_Support::getCacheName($this,'show-user'.$ID_st);
		
		/*
		 * Nacita vsetky data z cache, ak je mozne, inak z db
		 */
		if(!($data = $cache->load($cacheName))){			
			/*
			 * Zisti odbor, do ktoreho student patri 
			 */
			$studentMapper = new Db_Mapper_Student();
			$SkRokMapper = new Db_Mapper_SkRok();
			$TTridyMapper = new Db_Mapper_TTridy();
			$actualVznik = $SkRokMapper->getActual();
			$studentRow = $studentMapper->getTable()->find($ID_st)->current();
			$vznikSelect = $TTridyMapper->getTable()->select()
			->where('vznik = ?',$actualVznik->getID_sk(),Zend_Db::INT_TYPE)
			->order('Zkratka DESC');
			$group = $studentRow->findManyToManyRowset('Db_DbTable_TTridy','Db_DbTable_StudentHasTridy',null,null,$vznikSelect)->current();		
			$data['group'] = $group;
			
			/*
			 * Na zaklade zistenej skupiny vrati odborne bloky ktore ma dany odbor pridelene
			 */
			$blockMapper = new Db_Mapper_Block();
			$blocksSelect = $blockMapper->getTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
			$blocksSelect->join('block_St_obory','block_St_obory.bid=block.bid',array())
			->where('block_St_obory.Id_oboru = ?',$group->id_oboru,Zend_Db::INT_TYPE)
			->order('block.name');			
			$data['blocks'] = $blockMapper->fetchAll($blocksSelect);

			
			/*
			 * Naplni odorne bloky predmetami, ktore obsahuje
			 */				
			for ($i = 0; $i < count($data['blocks']); $i++) {
				$subjectMapper = new Db_Mapper_Subject();
				$select = $subjectMapper->getTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
				$select->order('subject.name');				
				$select->join('subject_block','subject_block.sid = subject.sid',array());
				$select->where('subject_block.bid = ?',$data['blocks'][$i]->bid,Zend_Db::INT_TYPE);							
				$data['blocks'][$i]->setSubjects($subjectMapper->fetchAll($select));
			}
			
			/*
			 * Zisti harmonogram pre studenta
			 */
			$harmonogramMapper = new Db_Mapper_Harmonogram();
			$data['harmonogram'] = $harmonogramMapper->fetchRow(
				$harmonogramMapper->getTable()->getAdapter()->quoteInto('ID_st = ?',$ID_st)
			);
						
			/*
			 * Pridelena tema bakalarskej prace
			 */
			$thesisMapper = new Db_Mapper_Thesis();
			$data['thesis'] = $thesisMapper->fetchRow(
				$thesisMapper->getTable()->getAdapter()->quoteInto('ID_st = ?',$ID_st)
			);
			
			$resultMapper = new Db_Mapper_Result();
			$selectResult = $resultMapper->getTable()->select()->where(
				$resultMapper->getTable()->getAdapter()->quoteInto('ID_st = ?',$ID_st)
			);
			
			$data['result'] = $resultMapper->fetchAll($selectResult);
			
			/*
			 * Ulozi do cache
			 */
			$cache->save($data,$cacheName,array('Result_ShowUser_ID_tr'.$group->ID_tr));
		}
		
		/*
		 * Ak nema student prideleny aspon jeden odborny blok,
		 * posle do view oznam o chybe, a view nedovoli pokracovat
		 */
		if(count($data['blocks']) <= 0){
			$this->view->blocksError = true;
		}
		
		/*
		 * Ak nie je este priradena tema z bc prace zobraz formular
		 */
		if($data['thesis'] == null){
			
			$jqueryParams = array(
			'url' => $this->view->url(array(
				'controller' => 'result',
				'action' => 'add-thesis',
				'format' => 'html',
				'ID_st' => $ID_st,
				)
			),
			'update' => 'div.dataContainer',
			'format' => 'html',
			);
			
			$data['thesis'] = new Form_Result_AddThesis($jqueryParams);
		}
		else {
			/*
			 * Ak je uz pridelena tema zobraz formular na pridelenie hodnotenia
			 */
			$jParams = array(
			'url' => $this->view->url(array(
				'controller' => 'result',
				'action' => 'add-thesis-mark',
				'format' => 'html',
				'tid' => $data['thesis']->getTid(),
				'ID_st' => $ID_st,
				)
			),			
			'update' => '.message',
			'format' => 'html',
			);			
			
			/*
			 * Nastavenie prarametrov pre ajax request pre formular
			 */
			$markForm = new Form_Result_SetThesisMark($jParams);
			
			/*
			 * Ak uz je pridelene hodnotenie za bc. pracu, tak ju vlozi do formulara
			 */
			if(isset($data['thesis']['mark'])){
				$markForm->getElement('markThesis')->setValue($data['thesis']['mark']);
			}
			
			/*
			 * Posle formular na pridelenie znamky z bc. prace do view
			 */
			$this->view->thesisMarkForm = $markForm;
			
			/*
			 * Ulozi do pola temu bc. prace, ktora sa pouzije potom na zobrazenie vo view
			 */
			$data['thesis'] = $data['thesis']->getName_cz() . '/' . $data['thesis']->getName_eng();
		}
				
		/*
		 * Odosiela hodnoty z controlleru do view
		 */
		$this->view->group = $data['group'];	
		$this->view->blocks = $data['blocks'];
		$this->view->harmonogram = $data['harmonogram'];
		$this->view->thesis = $data['thesis'];
		$this->view->results = $data['result'];					
	}
	
	
	/**
	 * Zobrazi dialog na pridelenie znamky, prip. poznamky
	 */
	public function showResultDialogAction(){
			
		$params = $this->getRequest()->getParams();
		
		/*
		 * Vytvori url, ktora povie formularu co a kam ma poslat(ajax request)
		 */
		$url = $this->view->url(array(
				'controller' => 'result',
				'action' => 'add-result',
				'format' => 'html',
				'ID_st' => (int)$params['ID_st'],
				'sid' => (int)$params['sid'],
				'rid' => isset($params['rid']) ? (int)$params['rid'] : null,
			),null,true
		);	
		
		/*
		 * Instancia formulara
		 */
		$addResultForm = new Form_Result_AddResult($url,'.dataContainer','html');
		
		/*
		 * Ak uz je pridelena znamky alebo poznamka, tak ju vloz do formulara
		 */
		if(isset($params['grade'])){
			$addResultForm->getElement('grade')->setValue($params['grade']);
		}		
		if(isset($params['note'])){
			$addResultForm->getElement('note')->setValue($params['note']);
		}
		
		$this->view->addResultForm = $addResultForm;
			
	}
	
	
	/**
	 * Akcia, ktora sa vola zo <code>showResultDialogAction()</code>. Ma na starosti
	 * ulozenie dat z formulara do db 
	 */
	public function addResultAction(){		
		
		$params = $this->getRequest()->getParams();
		
		$validator = new Zend_Validate_NotEmpty(); 
		
		if($validator->isValid($params['grade'])){		
			
			try{
								
				$data = array(
						'grade' => $params['grade'],
						'note' => empty($params['note']) ? NULL : $params['note'],
						'sid' => $params['sid'],
						'ID_st' => $params['ID_st'],
						'rid' => isset($params['rid']) ? $params['rid'] : null,
				);
				
				
				$resultMapper = new Db_Mapper_Result();
				$resultMapper->save(new Db_Model_Result($data));
				
				$this->view->message = '<p class="success">Hodnotenie pridané</p>';
				
				$cache = Zend_Registry::get('cache');
				$cache->remove(My_Support::getCacheName($this,'show-user'.$params['ID_st']));
				$cache->remove(My_Support::getCacheName('HarmonogramController','fetchAll'));				
				
				/*
				 * Presmeruje na showUserAction(), co sposobi, ze sa zobrazi akutalizovana stranka
				 * pre uzivatela 
				 */
				$this->_forward('show-user','result','default',array('id' => $params['ID_st'],'format' => 'html'));
				
			} catch(Zend_Db_Exception $e){
				
				$log = Zend_Registry::get('log');    		
	    		$log->log(get_class($e) . ':' . $e->getMessage(),Zend_Log::ERR);
	    			
	    		$this->view->message = '<p class="error">Hodnotenie sa nepodarilo pridať</p>';
			}
		}
		else {
			$this->view->errors = $validator->getMessages();
		}
	}
	
	/**
	 * Akcia, ktora sa vola z showUserAction(), ak nie je pridelene cislo otazok,
	 * z ktorych bude student odpovedat.
	 * 
	 * Ulozi cislo otazky do db.
	 */
	public function addQuestionNumberAction(){		
				
		$formData = $this->getRequest()->getPost();
		
		$validator = new My_Validate_GreaterThan(0);
		
		if($validator->isValid($formData['formInput'])){
			try{
								
				$qnForStudentMapper = new Db_Mapper_QnForStudent();
				$qnForStudentModel = new Db_Model_QnForStudent(array(
					'ID_st' => (int)$formData['studentID'],
					'qn_select' => (int)--$formData['formInput']// -1 lebo otazky sa cisluju od 0				
					)				
				);
				
				$qnForStudentMapper->save($qnForStudentModel,true);								
				
				
			} catch(Zend_Db_Exception $e){
				
				$log = Zend_Registry::get('log');    		
    			$log->log(get_class($e) . ':' . $e->getMessage(),Zend_Log::ERR);    			
    			$this->view->message = '<p class="error">Číslo otázky sa nepodarilo priradiť</p>';			
    			
			}					
		}
		else {			
			foreach($validator->getMessages() as $error){
				echo '<p class="error">' . $error . '</p>';
			}			
		}
		
		/*
		 * Presmerovanie na showUserAction()
		 */
		$this->_forward('show-user','result','default',array('id' => $formData['studentID'],'format' => 'html'));
	}
	
	/**
	 * Akcia, ktora sa vola z showUserAction(), pri prideleni temy bc. prace.
	 * Metoda ulozi cz a ang meno do db.
	 */
	public function addThesisAction(){
				
		$ID_st = (int)$this->getRequest()->getParam('ID_st');
		$params = $this->getRequest()->getParams();
		$validator = new Zend_Validate_NotEmpty();
				
		/*
		 * Ak nie je formular vyplneny spravne
		 */
		if(!$validator->isValid($params['name_cz']) || !$validator->isValid($params['name_eng'])){			
			foreach( $validator->getMessages() as $message){
				echo '<p class="error">' . $message . '</p>';
			}					
		}
		else {
			
			try{
				
				$thesisMapper = new Db_Mapper_Thesis();
				$thesisModel = new Db_Model_Thesis(array(
					'name_cz' => $params['name_cz'],
					'name_eng' => $params['name_eng'],
					'ID_st' => $ID_st,
					)
				);
				$insertedID = $thesisMapper->save($thesisModel);
				
				$cache = Zend_Registry::get('cache');				
				$cache->remove(My_Support::getCacheName($this,'show-user'.$ID_st));
				
			} catch(Zend_Exception $e){
				
				$log = Zend_Registry::get('log');    		
    			$log->log(get_class($e) . ':' . $e->getMessage(),Zend_Log::ERR);
			}			
		}
		/*
		 * Presmerovanie na show showUserAction()
		 */
		$this->_forward('show-user','result','default',array('id' => $ID_st,'format' => 'html'));
	}
	
	/**
	 * Metoda sa vola pri prideleni znamky z bc. prace a uklada data do db
	 */
	public function addThesisMarkAction(){
		$ID_st = (int)$this->getRequest()->getParam('ID_st');
		$tid = (int)$this->getRequest()->getParam('tid');
		$mark = $this->getRequest()->getParam('markThesis');
				
		try{
			$thesisMapper = new Db_Mapper_Thesis();
			$thesisMapper->save(new Db_Model_Thesis(array(
					'tid' => $tid,
					'mark' => $mark,
					)				
				)				
			);			
			$cache = Zend_Registry::get('cache');
			$cache->remove(My_Support::getCacheName($this,'show-user'.$ID_st));
			
		} catch(Zend_Db_Exception $e){				
			$log = Zend_Registry::get('log');    		
    		$log->log(get_class($e) . ':' . $e->getMessage(),Zend_Log::ERR);
		}
	}
	
	/**
	 * Zobrazuje dialog, ktory obsahuje predmety z daneho odborneho bloku na 
	 * zaklade id bloku.
	 */
	public function showBlockAction(){
		/**
		 * TODO dorobit cache		 
		 */
		$params = $this->getRequest()->getParams();
				
		/*
		 * Z db vyberie predmety pre dany blok na zaklade id bloku
		 */
		$blockMapper = new Db_Mapper_Block();
		$blockModel = $blockMapper->fetchWithDependentRowset(
			'Db_DbTable_Subject',
			'Db_DbTable_SubjectBlock',
			new Db_Model_Block(array('bid' => (int)$params['bid']))
		);

		$data['block'] = $blockModel[0];				
		
		/*
		 * Posle do view
		 */
		$this->view->block = $data['block'];
		$this->view->ID_st = $params['ID_st'];		
	}
	
	/**
	 * Metoda, ktora je volana z dialogu, ktory vytvori showBlockAction(), zobrazi
	 * text otazky pre studenta na zaklade jemu pridelenoho cisla otazky
	 */
	public function showQuestionAction(){
		
		/**
		 * TODO dorobit cache		 
		 */
		$sid = (int)$this->getRequest()->getParam('sid');
		$ID_st = (int)$this->getRequest()->getParam('ID_st');

		/*
		 * Zisti cislo otazky, ktore ma student pridelene
		 */
		$qnForStudentMapper = new Db_Mapper_QnForStudent();
		$qnForStudentModel = $qnForStudentMapper->fetchRow(
			$qnForStudentMapper->getTable()->getAdapter()->quoteInto('ID_st = ?',$ID_st,Zend_Db::INT_TYPE)
		);
		
		$data['qn'] = $qnForStudentModel->qn_select;
		
		/*
		 * Vyberie z db otazku
		 */
		$questionMapper = new Db_Mapper_Question();
		$select = $questionMapper->getTable()->select();
		$select->where(
			$questionMapper->getTable()->getAdapter()->quoteInto('sid = ? ',$sid,Zend_Db::INT_TYPE) .
			$questionMapper->getTable()->getAdapter()->quoteInto('AND qn = ? ',$data['qn'],Zend_Db::INT_TYPE) 
		);		
		$questionModel = $questionMapper->fetchAll($select);//model naplni datami
		$data['questions'] = $questionModel;
		
		$this->view->questions = $data['questions'];
		$this->view->qn = $data['qn'];
	}
	
	/**
	 * @deprecated Nepouziva sa, nahradi ju showBlockAction()
	 */
	public function showQuestionDialogAction(){
		$questionID = (int) $this->getRequest()->getParam('questionID');
		$studentID = (int) $this->getRequest()->getParam('studentID');
		$subjectID = (int) $this->getRequest()->getParam('subjectID');		
		
		$cache = Zend_Registry::get('cache');
		
		if(!($question = $cache->load('question' . $questionID))){
			$questionModel = new Db_Question();
			$question = $questionModel->find($questionID)->current();
			$cache->save($question,'question' . $questionID,array('questions'));	
		}		
		
		if(!($additionalQuestions = $cache->load('additionalQuestions' . $studentID . '' . $questionID))){
			$additionalQuestionModel = new Db_AdditionalQuestion();
			$additionalQuestions = $additionalQuestionModel->fetchAll(				
				$additionalQuestionModel->getAdapter()->quoteInto('ID_st = ? AND ',$studentID) .
				$additionalQuestionModel->getAdapter()->quoteInto('qid = ?',$questionID)
			);			
			$cache->save($additionalQuestions,'additionalQuestions' . $studentID . '' . $questionID,array('result'));			
		}
		
		$subjectModel = new Db_Subject();
		$subject = $subjectModel->find($question->sid)->current();
		
		
		$additionalQuestionForm = new Form_Result_AddAdditionalQuestion(null,$this->view->url(array(
				'controller' => 'result',
				'action' => 'add-additional-question',
				'format' => 'html'
				)
			 ),array('studentID' => $studentID,'questionID' => $questionID),'div.additionalQuestionContainer');		
		$this->view->additionalQuestions = $additionalQuestions;
		$this->view->additionalQuestionForm = $additionalQuestionForm;
		$this->view->subject = $subject;
		$this->view->question = $question;
	}
	
			
	/**
	 * @deprecated Momentalne sa nepouziva a pravdepodobne sa ani nebude
	 */
	public function addAdditionalQuestionAction(){
		
		$validator = new Zend_Validate_NotEmpty();
		$formData = $this->getRequest()->getPost();
		
		if($validator->isValid($formData['formInput'])){
			
			try{
				
				$additionalQuestionModel = new Db_AdditionalQuestion();
				
				$additionalQuestionModel->insert(
					array(
						'ID_st' => $formData['studentID'],
						'text' => $formData['formInput'],
						'qid' => $formData['questionID']
					)
				);
				
				$this->view->additionalQuestions = $additionalQuestionModel->fetchAll(
					$additionalQuestionModel->getAdapter()->quoteInto('ID_st = ? AND ',$formData['studentID']) .
					$additionalQuestionModel->getAdapter()->quoteInto('qid = ?',$formData['questionID'])
				);
				
				
				
				$cache = Zend_Registry::get('cache');
				$cache->remove('additionalQuestions' . $formData['studentID'] . '' . $formData['questionID']);
				
			} catch(Zend_Db_Exception $e){
				
				$log = Zend_Registry::get('log');    		
    			$log->log(get_class($e) . ':' . $e->getMessage(),Zend_Log::ERR);
    			
    			$this->view->message = '<p class="error">Otázku sa nepodarilo pridať</p>';
			}
		}
		else {
			
			$this->view->errors = $validator->getMessages();
		}
	}	
	
	/**
	 * Metody vola formular na zobrazenie studentov zo skupiny
	 */
	public function fillStudentsPanelAction(){
		
		$ID_tr = (int)$this->getRequest()->getParam('ID_tr');
		
		$studentMapper = new Db_Mapper_Student();
		$students = $studentMapper->fetchActualStudents(null,new Db_Model_TTridy(array('ID_tr' => $ID_tr)));
		
		$this->view->students = $students;
	}
}